package com.xubeihong.xubeihong;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

public class RSADemo {
    public static void main(String[] args) {
        try {
            // 生成 RSA 密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            // 待加密的明文
            String originalMessage = "这是要加密的消息";

            // 使用公钥加密
            byte[] encryptedMessage = encrypt(originalMessage.getBytes(), publicKey);
            System.out.println("原始消息：" + originalMessage);
            System.out.println("加密后的消息：" + new String(encryptedMessage));
            // 使用私钥解密
            byte[] decryptedMessage = decrypt(encryptedMessage, privateKey);

            System.out.println("解密后的消息：" + new String(decryptedMessage));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
}